package cn.xie.blog.serverutil.util;

import cn.xie.blog.model.common.enums.response.ResponseCodeEnum;
import cn.xie.blog.serverutil.constant.common.MailConstant;
import cn.xie.blog.serverutil.exception.BlogException;
import lombok.experimental.UtilityClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author: xiaoxie
 * create: 2025-04-22 18:50
 * @BelongsProject: blog-parent
 * @BelongsPackage: cn.xie.blog.serverutil.util
 * description: 发邮件工具类
 */
@UtilityClass
public class MailUtil {

    private static final Logger log = LoggerFactory.getLogger(MailUtil.class);

    public static boolean sendEmail(String recipient, String code) {
        // 发件人邮箱和授权码
        // QQ 邮箱的 SMTP 服务器地址
        // 设置属性
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", MailConstant.SMTP_SERVER); // 设置 SMTP 服务器
        properties.setProperty("mail.smtp.port", "587"); // 设置端口
        properties.setProperty("mail.smtp.auth", "true"); // 需要认证
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 启用 TLS 加密

        // 获取默认的 Session 对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MailConstant.USER, MailConstant.PASSWORD); // 设置发件人邮箱和授权码
            }
        });

        try {
            // 创建 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(MailConstant.USER));
            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            // 设置邮件主题
            message.setSubject(MailConstant.SUBJECT);
            // 设置邮件正文
            String content = "【xiaoxie】验证码"+ code + "用于网站注册，15分钟内有效，请勿泄露和转发。如非本人操作，请忽略此短信。";
            message.setText(content);
            // 发送邮件
            Transport.send(message);
            log.info("邮件发送成功！");
            return true;
        } catch (MessagingException e) {
            throw new BlogException(ResponseCodeEnum.MAIL_CODE_ERROR);

        }

    }

}
